import bitbrowser_api as api
import pyppeteer
import asyncio
import log

distance_list :list= ["1公里","2公里","5公里","10公里","20公里","40公里","60公里","80公里","100公里","250公里","500公里"]

async def edit_distance(ws_link,location :str, distance :int):
    """
    修改Marketplace中的位置
    param location: 位置,默认搜索出来的第一个
    param distance: 距离范围,是列表的第几个就输入几
    return: 成功返回True,失败返回False
    """

    """
    连接浏览器打开网页
    """
    # ws_link = api.get_pyppeteer_wslink_by_ids(api.get_alive_ids()[0])
    log.Info(f"Link to browser[{ws_link}]")

    # 连接浏览器
    browser = await pyppeteer.connect(
        browserWSEndpoint=ws_link,
        ignoreHTTPSErrors=True,
        args=['--no-sandbox']
    )
    log.Info(f"连接并打开网页https://www.facebook.com/marketplace/")
    # 创建新页面
    page = await browser.newPage()
    # 设置窗口大小为1024x768
    await page.setViewport({'width': 1024, 'height': 768})

    # 导航到目标 URL
    await page.goto("https://www.facebook.com/marketplace/")
    
    # 等待页面加载完成
    # await page.waitForSelector('body')


    try:
        """
        打开修改框
        """
        # 点击位置选择器
        location_selector = await page.waitForSelector(
            '.x193iq5w.xeuugli.x13faqbe.x1vvkbs.x1xmvt09.x1lliihq.x1s928wv.xhkezso.x1gmr53x.x1cpjm7i.x1fgarty.x1943h6x.xudqn12.x3x7a5m.x6prxxf.xvq8zen.x1s688f.x1fey0fg',
            timeout=10000
        )
        await location_selector.click()
        await asyncio.sleep(2)

        """
        修改位置
        """
        log.Info("修改位置")
        # 定位位置输入框
        location_input = await page.waitForSelector(
            '.x1i10hfl.xggy1nq.xtpw4lu.x1tutvks.x1s3xk63.x1s07b3s.x1kdt53j.x1a2a7pz.xjbqb8w.x1ejq31n.x18oe1m7.x1sy0etr.xstzfhl.x9f619.xzsf02u.x1uxerd5.x1fcty0u.x132q4wb.x1a8lsjc.xv54qhq.xf7dkkf.x9desvi.xh8yej3',
            timeout=10000
        )
        
        # 清空原有内容（如果有）
        await location_input.click({'clickCount': 3})  # 三击全选
        await location_input.press('Backspace')
        
        # 输入位置信息
        for char in location:
            await location_input.type(char)
            await asyncio.sleep(0.1)
        
        await asyncio.sleep(1)
        log.Info("位置输入成功")

        # 点击位置
        # 按下箭头键选择选项
        await page.keyboard.press('ArrowDown')
        await asyncio.sleep(0.2)

        # 按回车确认选择
        await page.keyboard.press('Enter')
        await asyncio.sleep(1)

        """
        修改半径范围
        """
        log.Info("修改半径范围")
        # 点击指定class的元素
        distance_selector = await page.waitForSelector(
            '.xjhjgkd.x1epquy7.x1ca8kz.x1562eck.xcclseo.x11lwdb5.xfxe0gy.x1szzd0g.xh2argp.x13fuv20.x18b5jzi.x1q0q8m5.x1t7ytsu.xq2ru2l.x1481eag.xjmv2fv.x1gx2yb3.x78zum5.xdt5ytf.x6ikm8r.x10wlt62.x1n2onr6.x1ja2u2z.x1bb484j.x1ypdohk.x1a2a7pz',
            timeout=10000
        )
        await distance_selector.click()
        await asyncio.sleep(1)
        
        # 按distance+1次下箭头键
        for _ in range(distance):
            await page.keyboard.press('ArrowDown')
            await asyncio.sleep(0.1)
        
        # 按回车确认选择
        await page.keyboard.press('Enter')
        await asyncio.sleep(1)
        
        """
        确认修改
        """
        log.Info("点击确认修改")
        try:
            # 使用XPath定位具有aria-label="应用"和指定class的div元素
            apply_button = await page.waitForXPath('//div[@aria-label="应用" and contains(@class, "x1i10hfl")]', timeout=10000)
            await apply_button.click()
            await asyncio.sleep(1)
        except:
            try:
                log.Info("备用方案")
                class_name = "x1i10hfl xjbqb8w x1ejq31n x18oe1m7 x1sy0etr xstzfhl x972fbf x10w94by x1qhh985 x14e42zd x1ypdohk xe8uvvx xdj266r x14z9mp xat24cr x1lziwak xexx8yu xyri2b x18d9i69 x1c1uobl x16tdsg8 x1hl2dhg xggy1nq x1fmog5m xu25z0z x140muxe xo1y3bh x87ps6o x1lku1pv x1a2a7pz x9f619 x3nfvp2 xdt5ytf xl56j7k x1n2onr6 xh8yej3"
                # 将class_name转换为CSS选择器
                selector = f".{class_name.replace(' ', '.')}"
                # 获取所有匹配的元素
                elements = await page.querySelectorAll(selector)

                # 点击第二个元素（索引为1）
                await elements[-1].click()
                await asyncio.sleep(1)
                log.Info("第二个指定class的元素点击成功")
            except Exception as e:
                log.Error(f"点击指定class的元素失败: {str(e)}")
                return False

    except Exception as e:
        log.Error(f"修改位置失败: {str(e)}")
        return False


if __name__ == "__main__":
    ws_link = api.get_pyppeteer_wslink_by_ids(api.get_alive_ids()[0])
    asyncio.run(edit_distance(ws_link,"北京",3))
